import path from 'path';

import fse from 'fs-extra';

import {runShouldFail, setDefaultStrictMode} from '../../common/common';
import {
  AbilityType,
  APIType,
  CaseLevel, CURRENT_HMOS_API,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: CURRENT_HMOS_API,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.StaticLibrary]: 1,
  },
};
/**
 *  1. 在har模块的src/main/ets/components/mainpage下增加MainPage.ts,保证和MainPage.ets同级
 *  2. 构建har包
 *  3. 检查std err是否存在对应告警
 */
const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {
  const projectRoot = project.projectRootPath();
  setDefaultStrictMode(projectRoot);
  // 获取har的源码路径src/main/ets/components
  const harPath = project.getModule('staticLibrary').moduleRootPath();
  const mainSrcPath = path.resolve(harPath, 'src', 'main', 'ets', 'components');
  const tsFilePath = path.resolve(mainSrcPath, 'MainPage.ts');
  // 创建重名空文件，并且该文件是被引用的
  if (!fse.existsSync(tsFilePath)) {
    fse.writeFileSync(tsFilePath, '');
  }
  // 构建har包
  const command = ['assembleHar'];

  const warningTobeContain = 'Duplicate file names detected, which may cause compilation errors. Please check the following files:';
  runShouldFail(projectRoot, command, warningTobeContain);
};

TestCaseBuilder.builder()
  .caseName('checkDuplicatedFileNames')
  .description('校验文件重名场景，发现重名需要做出warning')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testFun)
  .load();